import APIS from '@/apis';
import URLS from '@/apis/APIUrlDefine';
import Const from '@/common/Const';
import request from '@/utils/request';
import { PlusOutlined } from '@ant-design/icons';
import { Upload, Button } from 'antd';

import { RcCustomRequestOptions } from 'antd/lib/upload/interface';
import React, { useEffect, useState } from 'react';
import './index.css';

const VideoUpload: React.FC<any> = (props) => {
  const [showAddButton, updateAddButton] = useState(props.preVideo ? false : true);
  const [fileList, updateFileList] = props.preVideo
    ? useState<any>([
        {
          uid: Date.now(),
          percent: 100,
          url: URLS.SERVER_PICTURE_URL + props.preVideo,
          status: 'done',
        },
      ])
    : useState<any>([]);
  useEffect(() => {
    if (fileList.length > 0 &&fileList[0].url && fileList[0].url.endsWith(props.preVideo)) {
      return;
    }
    if (props.preVideo && props.preVideo.length > 0 ) {
      updateFileList([
        {
          uid: Date.now(),
          percent: 100,
          url: URLS.SERVER_PICTURE_URL + props.preVideo,
          status: 'done',
        },
      ]);
      updateAddButton(false);
    }
  });
  //自定义上传方法
  const customRequestUpload = async (option: RcCustomRequestOptions) => {
    var data = new FormData();
    updateFileList([
      {
        uid: option.file.uid,
        percent: 99,
        status: 'uploading',
      },
    ]);
    data.append('filename', option.file);
    data.append('type', '2');
    var result = await request('/api/utils/v1/upload', {
      method: 'POST',
      data: data,
    }).catch((ex) => {});
    if (result) {
      var asset = await APIS.AssetAPI.CreateNewAsset({
        url: result.data,
        type: Const.ASSET_TYPE.VIDEO_TYPE,
      }).catch(() => {});
      updateFileList([
        {
          uid: option.file.uid,
          percent: 100,
          url: URLS.SERVER_PICTURE_URL + asset.data?.url,
          status: asset.data ? 'done' : 'error',
        },
      ]);
      props.handleVideoChange?.(result.data);
    }
  };

  return (
    <div style={{ display: 'flex' }}>
      <Upload
        accept=".mp4"
        className="uplaod-image-btn"
        showUploadList={{ showPreviewIcon: true, showRemoveIcon: true }}
        multiple={false}
        name="logo"
        action="/upload.do"
        onRemove={() => {
          updateAddButton(true);
          updateFileList([]);
          props.handleVideoChange?.(null);
        }}
        fileList={fileList}
        customRequest={customRequestUpload}
        onChange={({ fileList }) => {
          updateAddButton(fileList.length === 0);
          updateFileList(fileList);
        }}
        listType="picture-card"
      >
        {/* {console.log(fileList)} */}
        {showAddButton ? <Button icon={<PlusOutlined />}></Button> : null}
      </Upload>
    </div>
  );
};

export default VideoUpload;
